package com.zb.manager.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.zb.model.*;
import com.zb.service.ListMsgService;
import com.zb.service.SysService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class SysAction {

	@Autowired(required=true)
	private SysService ss;
	
	@Autowired(required=true)
	private ListMsgService ls;
	
	/**
	 * 轮播图片设置-访问前获取数据
	 * 如果处于未登录状态则无法访问该模块
	 * @param request
	 * @return
	 */
	@GetMapping("/sysInit")
	public String sysInit(HttpServletRequest request){
		if(request.getSession().getAttribute("admin")==null) {
			request.setAttribute("msg", "请先登录!!");
			return "../index";
		}
		List<SysDes> sysDess =  ss.findAllByType(0);
		request.setAttribute("sysDes", sysDess);
		request.setAttribute("size", sysDess.size());
		return "lcx/sysdesigner";
	}
	
	/**
	 * 轮播图片设置-上传轮播图片
	 * 使用layui实现图片上传
	 * @param file
	 * @param reponse
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/uploadlunbo",method=RequestMethod.POST)
	public String uploadlunbo(MultipartFile file,HttpServletResponse reponse) {
		if(file==null) {                                //判断是否有文件传输到后台
			LayuiUploadResponse lur = new LayuiUploadResponse();
			lur.setCode(1);
			lur.setMsg("后台没有接收到数据");
			return new Gson().toJson(lur);
		}
		System.out.println("===========>"+file.getOriginalFilename());
		LayuiUploadResponse rlur = ss.uploadlunbo(file);//对图片文件的处理放到service层
		return new Gson().toJson(rlur);
	}
	
	/**
	 * 轮播图片设置-删除轮播图片
	 * @param sysid
	 * @return
	 */
	@ResponseBody
	@GetMapping("/delsysphoto")
	public int delsysphoto(String sysid) {
		
		return ss.deleteSysById(sysid);
	}
	
	/**
	 * 主页在加载前获取的轮播图片
	 * ajax传输
	 * @return
	 */
	@ResponseBody
	@GetMapping("/indexInit")
	public List<SysDes> indexInit(){
		return ss.findAllByType(0);
	}
	
	/**
	 * 公告内容-图片回显
	 * @param myFileName
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/noticeImgUpload",method=RequestMethod.POST)
	public  String noticeImgUpload(MultipartFile myFileName,HttpServletRequest request,HttpServletResponse response) {
		String url;
		if (myFileName != null) {
			String fileName = myFileName.getOriginalFilename();
			String fileNameExtension = fileName.substring(fileName.indexOf("."), fileName.length());//解析文件后缀名
			String realName = UUID.randomUUID().toString() + fileNameExtension;//重新生成文件名
			String realPath = "D:\\Program_Files\\apache-tomcat-8.5.32\\webapps\\moyissm\\static\\noticeimg\\"; //定义文件存放位置（在该服务器的哪个地方存放图片）
			url="http://127.0.0.1:8080/moyissm/static/noticeimg/"+realName; //设置该图片的访问路径
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(realPath + realName);
				IOUtils.copy(myFileName.getInputStream(), fos); //将从客户端接收到的图片以字节流的形式输出到存放文件的地方
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			List<String> imgUrlList = new ArrayList<String>();
			imgUrlList.add(url);
			EditImgMsg eim = new EditImgMsg();
			eim.setErrno(0);
			eim.setData(imgUrlList);
			return new Gson().toJson(eim);
		}else {
			return null;
		}
	}
	
	/**
	 * 发布公告-添加公告
	 * 接收公告内容->上传到服务器->生成访问链接->保存到数据库中
	 * @param value
	 * @param noticeTitle
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/addNotice",method=RequestMethod.POST)
	public int addNotice(String value,String noticeTitle,HttpServletRequest request){
		//判断值是否为空
		System.out.println("====noticeTitle==>"+noticeTitle+"====");
		//User user = (User) request.getSession().getAttribute("user");
//		User user = new User();
//		user.setStatus(1);
//		if(user==null) {
//			request.setAttribute("msg", "您还没有登录，请登录后访问！！");
//			return 3;
//		}
//		if(user.getStatus()!=1) {
//			request.setAttribute("msg", "您不是管理员，没有操作权限！！");
//			return 4;
//		}
//		if(noticeTitle==null||noticeTitle.equals("")||noticeTitle.equals(" ")) {
//			request.setAttribute("msg", "没有填写文章名称，请刷新后重新填写！！");
//			return 2;
//		}
		
		TAdmin admin = (TAdmin) request.getSession().getAttribute("admin");
		//admin.setStatus(1);
		if(admin==null) {
			request.setAttribute("msg", "您还没有登录，请登录后访问！！");
			return 3;
		}
//		if(user.getStatus()!=1) {
//			request.setAttribute("msg", "您不是管理员，没有操作权限！！");
//			return 4;
//		}
		if(noticeTitle==null||noticeTitle.equals("")||noticeTitle.equals(" ")) {
			request.setAttribute("msg", "没有填写文章名称，请刷新后重新填写！！");
			return 2;
		}
		
		//接收文章，传输到服务器
		System.out.println("=========>"+value);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date(); //公告发布时间
		String formatDate = sdf.format(date);
		String uuid = UUID.randomUUID().toString();
		String aName =noticeTitle + "-" +uuid; //公告名字设置：公告标题-36位随机数。html
		
		//设置上传路径
		String path = "D:\\Program_Files\\apache-tomcat-8.5.32\\webapps\\moyissm\\static\\notice\\"; //设置访问路径
		try {
			FileWriter fw = new FileWriter(path+aName+".html"); //创建文件
			value="<html>" + 
					"	<head>" + 
					"<meta http-equiv=\'Content-Type\' content=\'text/html; charset=utf-8\' />"+
					"		<title></title>" + 
					"	</head>" + 
					"	<body>" + value+
					"	</body>" + 
					"</html>";
			fw.write(value);  //以字符流写数据
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//生成访问URL
		String listurl = "http://127.0.0.1:8080/moyissm/static/notice/"+aName+".html";
		System.out.println("===url:====>"+listurl);
		
		//生成entity实例，传到数据库中
		SysDes sd = new SysDes(); 
		sd.setCreate_time(date);
		sd.setSysid(uuid);
		sd.setTitle(noticeTitle);
		sd.setUrl(listurl);
		sd.setType(1);
		String admin_name = (String) request.getSession().getAttribute("admin_name");
		
//		sd.setDetail("系统管理员"+user.getUser_name()+"在"+formatDate+"发布了该公告");
		sd.setDetail("系统管理员"+admin_name+"在"+formatDate+"发布了该公告");
		//上传到数据库中
		return ss.addNotice(sd);
	}
	
	/**
	 * 公告发布-公告管理-访问前获取数据
	 * 数据分页
	 * @param request
	 * @param mm
	 * @param pageNo
	 * @return
	 */
	@GetMapping("/noticeManagerInit")
	public String noticeManagerInit(HttpServletRequest request, ModelMap mm,@RequestParam(defaultValue="1",required=true,value="pageNo")Integer pageNo) {
		Integer pageSize = 8;
		PageHelper.startPage(pageNo, pageSize);
		List<SysDes> sysdes = ss.findAllByType(1);
		PageInfo<SysDes> lms  = new PageInfo<SysDes>(sysdes);
		mm.addAttribute("pageInfo",lms);
		request.setAttribute("size", sysdes.size());
		return "lcx/noticeManager-show";
	}
	
	/**
	 * 删除公告
	 * ajax
	 * @param sysId
	 * @return
	 */
	@ResponseBody
	@GetMapping("/delnoticebyid")
	public int delnoticebyid(HttpServletRequest request,String sysId) {
		String noticeid=request.getParameter("noticeid");
		System.out.println("-------noticeid is " + noticeid);
		sysId=noticeid;
		return ss.deleteSysById(sysId);
	}
	
	/**
	 * 首页获取公告（最近发布的前六个）
	 * ajax首页获取数据
	 * @return
	 */
	@ResponseBody
	@GetMapping("/indexNoticeInit")
	public List<SysDes> indexNoticeInit(){
		return ss.findSomeNotice();
	}
	
	/**
	 * 访问活动公告页面-子页面加载数据
	 * 数据分页
	 * @param request
	 * @param mm
	 * @param pageNo
	 * @return
	 */
	@GetMapping("/actityNoticeInit")
	public String actityNoticeInit(HttpServletRequest request, ModelMap mm,@RequestParam(defaultValue="1",required=true,value="pageNo")Integer pageNo){
		Integer pageSize = 15;
		PageHelper.startPage(pageNo, pageSize);
		List<SysDes> sysdes = ss.findAllByType(1);
		PageInfo<SysDes> lms  = new PageInfo<SysDes>(sysdes);
		mm.addAttribute("pageInfo",lms);
		request.setAttribute("size", sysdes.size());
		return "user/activity-show";
	}
	
	/**
	 * 访问非遗清单页面-子页面加载数据
	 * 数据分页
	 * @param request
	 * @param mm
	 * @param pageNo
	 * @param type
	 * @return
	 */
	@GetMapping("/listInit")
	public String listInit(HttpServletRequest request, ModelMap mm,@RequestParam(defaultValue="1",required=true,value="pageNo")Integer pageNo,int type){
		Integer pageSize = 8;
		PageHelper.startPage(pageNo, pageSize);
		List<ListMsg> listmsgs = ls.selectListMadByType(type);
		PageInfo<ListMsg> lms  = new PageInfo<ListMsg>(listmsgs);
		mm.addAttribute("pageInfo",lms);
		request.setAttribute("size", listmsgs.size());
		request.setAttribute("type", type);
		return "user/list-show";
	}
	
	/**
	 * 添加热门专题
	 * 最多添加三个
	 * @param request
	 * @param sd
	 * @return
	 */
	@ResponseBody
	@GetMapping("/addhotspecial")
	public int addhotspecial(HttpServletRequest request,SysDes sd) {
		if(request.getSession().getAttribute("user")==null) {
			return 2;
		}
		if(ss.findAllByType(2).size()==3) {
			return 3;
		}
		System.out.println("======>title===>"+sd.getTitle());
		System.out.println("======>listtype===>"+sd.getListtype());
		sd.setSysid(UUID.randomUUID().toString());
		sd.setType(2);
		sd.setCreate_time(new Date());
		sd.setDetail("设置首页的热门专题");
		return ss.addNotice(sd);
	}
	
	/**
	 * 系统设置-热门专题-访问前加载
	 * @return
	 */
	@ResponseBody
	@GetMapping("/hotspecialsysInit")
	public List<SysDes> hotspecialsysInit(){
		return ss.findAllByType(2);
	}
	
	/**
	 * 系统设置-热门专题-删除热门专题
	 * @param request
	 * @param listtype
	 * @return
	 */
	@ResponseBody
	@GetMapping("/delhotspecial")
	public int delhotspecial(HttpServletRequest request,int listtype) {
		if(request.getSession().getAttribute("user")==null) {
			return 2;
		}
		return ss.deleteHotSpecialByType(listtype);
	}
	
	@GetMapping("/index.do")
	public String indexHotSpecialInit(HttpServletRequest request){
		List<IndexDes> ids =ss.indexInit();
		request.setAttribute("index", ids);
		return "lcx/index";
	}
	
}
